<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI Image Chat</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Arial', sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
    }

    .chat-container {
      background: white;
      border-radius: 20px;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
      width: 100%;
      max-width: 800px;
      overflow: hidden;
    }

    .chat-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px;
      text-align: center;
    }

    .chat-header h1 {
      font-size: 24px;
      margin-bottom: 5px;
    }

    .chat-header p {
      opacity: 0.9;
      font-size: 14px;
    }

    .modal {
      display: none;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 300px;
      text-align: center;
      border-radius: 10px;
      position: relative;
    }

    .close-btn {
      position: absolute;
      top: 10px;
      right: 15px;
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    .close-btn:hover,
    .close-btn:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }

    #qrcode {
      width: 100%;
      max-width: 256px;
      height: auto;
      margin-top: 10px;
    }

    .chat-messages {
      padding: 20px;
      height: 400px;
      overflow-y: auto;
      background: #f8f9fa;
    }

    .message {
      margin-bottom: 15px;
      display: flex;
      align-items: flex-start;
    }

    .message.user {
      justify-content: flex-end;
    }

    .message-content {
      max-width: 70%;
      padding: 12px 16px;
      border-radius: 18px;
      word-wrap: break-word;
    }

    .message.user .message-content {
      background: #667eea;
      color: white;
      border-bottom-right-radius: 4px;
    }

    .message.bot .message-content {
      background: white;
      color: #333;
      border: 1px solid #e0e0e0;
      border-bottom-left-radius: 4px;
    }

    .image-response {
      margin-top: 10px;
      text-align: center;
    }

    .image-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 10px;
      margin-top: 10px;
    }

    .image-item {
      position: relative;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s ease;
    }

    .image-item:hover {
      transform: scale(1.02);
    }

    .image-item img {
      width: 100%;
      height: 150px;
      object-fit: cover;
      display: block;
    }

    .image-actions {
      position: absolute;
      top: 5px;
      right: 5px;
      display: flex;
      gap: 5px;
    }

    .action-btn {
      background: rgba(255, 255, 255, 0.9);
      border: none;
      border-radius: 50%;
      width: 30px;
      height: 30px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    .action-btn:hover {
      background: white;
      transform: scale(1.1);
    }

    .regenerate-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      font-size: 12px;
      cursor: pointer;
      margin-top: 10px;
      transition: all 0.3s ease;
    }

    .regenerate-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .add-more-btn {
      background: #28a745;
      color: white;
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      font-size: 12px;
      cursor: pointer;
      margin-top: 10px;
      margin-left: 10px;
      transition: all 0.3s ease;
    }

    .add-more-btn:hover {
      background: #218838;
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }

    .chat-input {
      padding: 20px;
      background: white;
      border-top: 1px solid #e0e0e0;
    }

    .input-group {
      display: flex;
      gap: 10px;
    }

    .chat-input input {
      flex: 1;
      padding: 12px 16px;
      border: 2px solid #e0e0e0;
      border-radius: 25px;
      font-size: 16px;
      outline: none;
      transition: border-color 0.3s ease;
    }

    .chat-input input:focus {
      border-color: #667eea;
    }

    .send-btn {
      padding: 12px 24px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 25px;
      cursor: pointer;
      font-size: 16px;
      font-weight: bold;
      transition: transform 0.2s ease;
    }

    .send-btn:hover {
      transform: translateY(-2px);
    }

    .send-btn:active {
      transform: translateY(0);
    }

    .loading {
      display: none;
      text-align: center;
      padding: 20px;
      color: #666;
    }

    .loading.show {
      display: block;
    }

    .spinner {
      border: 3px solid #f3f3f3;
      border-top: 3px solid #667eea;
      border-radius: 50%;
      width: 30px;
      height: 30px;
      animation: spin 1s linear infinite;
      margin: 0 auto 10px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .placeholder-text {
      color: #999;
      font-style: italic;
      text-align: center;
      padding: 40px 20px;
    }

    @media (max-width: 600px) {
      .chat-container {
        margin: 10px;
      }

      .message-content {
        max-width: 85%;
      }

      .input-group {
        flex-direction: column;
      }

      .send-btn {
        width: 100%;
      }

      .image-grid {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
<div class="chat-container">
  <div class="chat-header">
    <h1>AI Image Generator</h1>
    <p>输入描述，获取AI生成的图片</p>
  </div>

  <div class="chat-messages" id="chatMessages">
    <div class="placeholder-text">
      <p>🤖 欢迎使用AI图片生成器！</p>
      <p>请在下方输入框中描述您想要的图片，我将为您生成相应的图片。</p>
      <p>例如："一只可爱的小猫在花园里玩耍"</p>
    </div>
  </div>

  <div class="loading" id="loading">
    <div class="spinner"></div>
    <p>正在生成图片，请稍候...</p>
  </div>

  <div class="chat-input">
    <div class="input-group">
      <input type="text" id="messageInput" placeholder="描述您想要的图片..." maxlength="200">
      <button class="send-btn" id="sendBtn">发送</button>
    </div>

  </div>
</div>

<div id="loginModal" class="modal">
  <div class="modal-content">
    <span class="close-btn">&times;</span>
    <h2>Scan to Login</h2>
    <img id="qrcode" src="" alt="QR Code">
  </div>
</div>

<script>
  const chatMessages = document.getElementById('chatMessages');
  const messageInput = document.getElementById('messageInput');
  const sendBtn = document.getElementById('sendBtn');
  const loading = document.getElementById('loading');

  const modal = document.getElementById('loginModal');
  const closeBtn = modal.querySelector('.close-btn');
  const qrcodeImg = document.getElementById('qrcode');

  // 页面加载时自动获取二维码
  window.addEventListener('load', () => {
    messageInput.focus();
    // 自动获取二维码
    fetch('/login')
            .then(response => response.json())
            .then(data => {
              qrcodeImg.src = `${data.imageData}`;
              modal.style.display = 'block';
            })
            .catch(error => console.error('Error fetching QR code:', error));
  });

  closeBtn.addEventListener('click', () => {
    modal.style.display = 'none';
  });

  window.addEventListener('click', (event) => {
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  });


  // 存储每个消息的图片数据
  const messageImages = new Map();

  function addMessage(content, isUser = false) {
    // 移除占位符文本
    const placeholder = chatMessages.querySelector('.placeholder-text');
    if (placeholder) {
      placeholder.remove();
    }

    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isUser ? 'user' : 'bot'}`;

    const messageContent = document.createElement('div');
    messageContent.className = 'message-content';
    messageContent.textContent = content;

    messageDiv.appendChild(messageContent);
    chatMessages.appendChild(messageDiv);

    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;

    return messageDiv;
  }

  function addImage(imageUrl, messageDiv, imageIndex = 0) {
    let imageResponse = messageDiv.querySelector('.image-response');
    if (!imageResponse) {
      imageResponse = document.createElement('div');
      imageResponse.className = 'image-response';
      messageDiv.querySelector('.message-content').appendChild(imageResponse);
    }

    let imageGrid = imageResponse.querySelector('.image-grid');
    if (!imageGrid) {
      imageGrid = document.createElement('div');
      imageGrid.className = 'image-grid';
      imageResponse.appendChild(imageGrid);
    }

    const imageItem = document.createElement('div');
    imageItem.className = 'image-item';
    imageItem.dataset.imageIndex = imageIndex;

    const img = document.createElement('img');
    img.src = imageUrl;
    img.alt = 'Generated Image';

    const imageActions = document.createElement('div');
    imageActions.className = 'image-actions';

    const refreshBtn = document.createElement('button');
    refreshBtn.className = 'action-btn';
    refreshBtn.innerHTML = '🔄';
    refreshBtn.title = '重新生成此图片';
    refreshBtn.onclick = () => regenerateSingleImage(messageDiv, imageIndex);

    const downloadBtn = document.createElement('button');
    downloadBtn.className = 'action-btn';
    downloadBtn.innerHTML = '⬇';
    downloadBtn.title = '下载图片';
    downloadBtn.onclick = () => downloadImage(imageUrl);

    imageActions.appendChild(refreshBtn);
    imageActions.appendChild(downloadBtn);

    imageItem.appendChild(img);
    imageItem.appendChild(imageActions);
    imageGrid.appendChild(imageItem);

    // 添加按钮组
    let buttonGroup = imageResponse.querySelector('.button-group');
    if (!buttonGroup) {
      buttonGroup = document.createElement('div');
      buttonGroup.className = 'button-group';
      imageResponse.appendChild(buttonGroup);

      const regenerateBtn = document.createElement('button');
      regenerateBtn.className = 'regenerate-btn';
      regenerateBtn.textContent = '🔄 重新生成全部';
      regenerateBtn.onclick = () => regenerateAllImages(messageDiv);

      const addMoreBtn = document.createElement('button');
      addMoreBtn.className = 'add-more-btn';
      addMoreBtn.textContent = '➕ 添加更多图片';
      addMoreBtn.onclick = () => addMoreImages(messageDiv);

      buttonGroup.appendChild(regenerateBtn);
      buttonGroup.appendChild(addMoreBtn);
    }

    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }

  function showLoading() {
    loading.classList.add('show');
  }

  function hideLoading() {
    loading.classList.remove('show');
  }

  function generateImage(prompt) {
    // 这里可以替换为实际的API调用
    return new Promise((resolve) => {
      setTimeout(() => {
        // 随机选择一个示例图片
        const randomImage = sampleImages[Math.floor(Math.random() * sampleImages.length)];
        resolve(randomImage);
      }, 2000); // 模拟2秒的处理时间
    });
  }

  function generateMultipleImages(prompt, count = 3) {
    return Promise.all(
        Array(count).fill().map(() => generateImage(prompt))
    );
  }

  async function regenerateSingleImage(messageDiv, imageIndex) {
    const messageId = messageDiv.dataset.messageId;
    const prompt = messageImages.get(messageId)?.prompt || '';

    if (!prompt) return;

    showLoading();

    try {
      const newImageUrl = await generateImage(prompt);
      const imageItem = messageDiv.querySelector(`[data-image-index="${imageIndex}"]`);
      if (imageItem) {
        const img = imageItem.querySelector('img');
        img.src = newImageUrl;
      }
    } catch (error) {
      console.error('重新生成图片失败:', error);
    } finally {
      hideLoading();
    }
  }

  async function regenerateAllImages(messageDiv) {
    const messageId = messageDiv.dataset.messageId;
    const prompt = messageImages.get(messageId)?.prompt || '';

    if (!prompt) return;

    showLoading();

    try {
      const newImages = await generateMultipleImages(prompt, 3);
      const imageGrid = messageDiv.querySelector('.image-grid');
      if (imageGrid) {
        imageGrid.innerHTML = '';
        newImages.forEach((imageUrl, index) => {
          addImage(imageUrl, messageDiv, index);
        });
      }
    } catch (error) {
      console.error('重新生成所有图片失败:', error);
    } finally {
      hideLoading();
    }
  }

  async function addMoreImages(messageDiv) {
    const messageId = messageDiv.dataset.messageId;
    const prompt = messageImages.get(messageId)?.prompt || '';

    if (!prompt) return;

    showLoading();

    try {
      const newImages = await generateMultipleImages(prompt, 2);
      const currentImageCount = messageDiv.querySelectorAll('.image-item').length;
      newImages.forEach((imageUrl, index) => {
        addImage(imageUrl, messageDiv, currentImageCount + index);
      });
    } catch (error) {
      console.error('添加更多图片失败:', error);
    } finally {
      hideLoading();
    }
  }

  function downloadImage(imageUrl) {
    const link = document.createElement('a');
    link.href = imageUrl;
    link.download = `generated-image-${Date.now()}.jpg`;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  async function sendMessage() {
    const message = messageInput.value.trim();
    if (!message) return;

    // 添加用户消息
    const userMessageDiv = addMessage(message, true);

    // 清空输入框
    messageInput.value = '';

    // 显示加载状态
    showLoading();

    try {
      // 调用publish接口
      const response = await fetch(`/publish?message=${encodeURIComponent(message)}`);
      const data = await response.json();

      // 隐藏加载状态
      hideLoading();

      // 根据ChatsDto参数修改发送后返回内容
      // 添加标题
      const titleMessageDiv = addMessage(`标题: ${data.title}`);

      // 添加内容
      const contentMessageDiv = addMessage(data.content);

      // 添加图片描述
      const descMessageDiv = addMessage(`图片描述: ${data.imageDesc}`);

      const messageId = `msg-${Date.now()}`;
      titleMessageDiv.dataset.messageId = messageId;
      contentMessageDiv.dataset.messageId = messageId;
      descMessageDiv.dataset.messageId = messageId;

      // 存储消息数据
      messageImages.set(messageId, {
        prompt: message,
        images: [data.imageUrl]
      });

      // 添加图片到消息
      addImage(data.imageUrl, titleMessageDiv, 0);

    } catch (error) {
      hideLoading();
      addMessage('抱歉，生成图片时出现错误，请稍后重试。');
      console.error('Error:', error);
    }
  }

  // 事件监听器
  sendBtn.addEventListener('click', sendMessage);

  messageInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      sendMessage();
    }
  });

  // 页面加载完成后聚焦输入框
  window.addEventListener('load', () => {
    messageInput.focus();
  });
</script>
</body>
</html>